import os
import pandas as pd

def analyze_test_case_multiple_files(directory, test_case_prefix):
    # Find all files that match the test case prefix
    all_files = [f for f in os.listdir(directory) if f.startswith(test_case_prefix) and f.endswith('.csv')]
    if not all_files:
        print(f"No files found for test case prefix: {test_case_prefix}")
        return

    summary_rows = []

    print(f"Calculating metrics for each file in test case prefix: {test_case_prefix}\n")
    for file in all_files:
        file_path = os.path.join(directory, file)
        try:
            # Open files in read-only mode with correct encoding and separator
            with open(file_path, 'r', encoding="utf-16") as f:
                df = pd.read_csv(f, sep="\t")

            # Calculate metrics for the current file
            avg_cpu = df["Total CPU Usage (%)"].mean()
            max_memory = df["Total Memory Usage (MB)"].max()
            avg_thread = df["Total Thread Count"].mean()

            # Print metrics for the current file
            print(f"File: {file}")
            print(f"  Average CPU Usage: {avg_cpu:.2f}%")
            print(f"  Maximum Memory Usage: {max_memory:.2f} MB")
            print(f"  Average Thread Count: {avg_thread:.2f}\n")

            # Append metrics to summary_rows
            summary_rows.append({
                "File": file,
                "Average CPU Usage (%)": avg_cpu,
                "Maximum Memory Usage (MB)": max_memory,
                "Average Thread Count": avg_thread
            })
        except Exception as e:
            print(f"Error reading file {file}: {e}")
            continue

    # Create a DataFrame for the summaries
    summary_df = pd.DataFrame(summary_rows)

    if summary_df.empty:
        print(f"No valid data found for test case prefix: {test_case_prefix}")
        return

    # Calculate overall metrics across all files
    overall_avg_cpu = summary_df["Average CPU Usage (%)"].mean()
    overall_avg_memory = summary_df["Maximum Memory Usage (MB)"].mean()
    overall_avg_thread = summary_df["Average Thread Count"].mean()

    # Print the summary DataFrame and overall metrics
    print(f"\nSummary Data for All Files:")
    print(summary_df)
    print(f"\nOverall Metrics Across All Files for Test Case Prefix: {test_case_prefix}")
    print(f"  Overall Average CPU Usage: {overall_avg_cpu:.2f}%")
    print(f"  Overall Maximum Memory Usage: {overall_avg_memory:.2f} MB")
    print(f"  Overall Average Thread Count: {overall_avg_thread:.2f}")

# Example usage
directory = 'C:/Users/Win/Desktop/codes/test_result/Cypress/'  # Replace with the correct directory
test_case_prefix = 'testcase_three'  # Replace with the desired test case prefix
analyze_test_case_multiple_files(directory, test_case_prefix)
